#include "../logs/dhylog.hpp"
#include"unistd.h"
enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY,
};
class RollByTimeSink : public dhylog::LogSink
{
public:
    using ptr = std::shared_ptr<RollByTimeSink>;
    RollByTimeSink(const std::string &basename, TimeGap gap_type) : _basename(basename)
    {
        switch (gap_type)
        {
        case TimeGap::GAP_SECOND:
            _gap_size = 1;
            break;
        case TimeGap::GAP_MINUTE:
            _gap_size = 60;
            break;
        case TimeGap::GAP_HOUR:
            _gap_size = 6060;
            break;
        case TimeGap::GAP_DAY:
            _gap_size = 360024;
            break;
        }
        _cur_gap = _gap_size==1?dhylog::util::date::now():dhylog::util::date::now() % _gap_size; //获取当前时间段
        std::string filename = createFilename();
        dhylog::util::File::create_directory(dhylog::util::File::path(filename));
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }

    void log(const char *data, size_t len) override
    {
        time_t cur = dhylog::util::date::now();
        if ((cur % _gap_size) != _cur_gap)
        {
            _ofs.close();
            std::string filename = createFilename();
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }
        _ofs.write(data, len);
        if (_ofs.good() == false)
        {
            std::cout << "日志文件输出失败" << std::endl;
        }
    }

private:
    std::string createFilename()
    {
        time_t t = dhylog::util::date::now();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream ss;
        ss << _basename;
        ss << lt.tm_year + 1900;
        ss << "-";
        ss << lt.tm_mon + 1;
        ss << "-";
        ss << lt.tm_mday;
        ss << "-";
        ss << lt.tm_hour;
        ss << "-";
        ss << lt.tm_min;
        ss << "-";
        ss << lt.tm_sec;
        ss << ".log";
        return ss.str();
    }
private:
    std::string _basename;
    std::ofstream _ofs;
    size_t _cur_gap; //当前时间段
    size_t _gap_size; //时间段大小
};
int main()
{
    std::unique_ptr<dhylog::LoggerBuilder> builder(new dhylog::GlobalLoggerBuilder());
    builder->buildLoggerName("async_logger");
    builder->buildLoggerLevel(dhylog::loglevel::value::WARN);
    builder->buildFormatter("[%c][%f:%l]%m%n");
    builder->buildLoggerType(dhylog::LoggerType::LOGGER_ASYNC);
    //builder->buildEnableUnSafeAsync();
    builder->buildSink<RollByTimeSink>("./logfile/roll-async-by-time",TimeGap::GAP_SECOND);

    dhylog::Logger::ptr logger=builder->build();
    size_t cur=dhylog::util::date::now();
    while(dhylog::util::date::now()<cur+5)
    {
        logger->fatal("这是一条测试日志");
        usleep(1000);
    }
    return 0;
}
